package fw_cron

import (
	"github.com/go-co-op/gocron/v2"
	"github.com/google/uuid"
	"mysql_bak/fw_bak"
	"mysql_bak/fw_config"
	"mysql_bak/fw_log"
)

var scheduler gocron.Scheduler

func CronInit() {
	go func() {
		var err error
		scheduler, err = gocron.NewScheduler()
		if err != nil {
			return
		}
		err = BakMysql()
		fw_log.Slogger.Info("BakMysql", err)
		for {
			defer scheduler.Shutdown()
			// start the scheduler
			scheduler.Start()
			select {}
		}
	}()
}

func RemoveJobByUuID(uuid uuid.UUID) error {
	return scheduler.RemoveJob(uuid)
}
func RemoveJobWithTags(tags string) {
	scheduler.RemoveByTags(tags)
}

func GetScheduler() gocron.Scheduler {
	return scheduler
}

func GetJobs() []gocron.Job {
	return scheduler.Jobs()
}

func GetJobByTag(tag string) bool {
	jobs := scheduler.Jobs()
	if len(jobs) <= 0 {
		return false
	}
	for _, v := range jobs {
		if len(v.Tags()) > 0 {
			if v.Tags()[0] == tag {
				return true
			}
		}
	}
	return false
}

func BakMysql() error {
	_, err := scheduler.NewJob(
		gocron.CronJob(
			fw_config.GetConfigHandler().GetString("cron"),
			true,
		),
		gocron.NewTask(
			func() {
				fw_bak.Backup()
			},
		),
		gocron.WithTags("BakMysql"),
		gocron.WithSingletonMode(gocron.LimitModeWait),
	)
	if err != nil {
		return err
	}
	return nil
}
